public class buildTreeUsedPostAndInOrder {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length - 1;
        return buildTreeChild(inorder,postorder,0,inorder.length - 1);
    }
    public int postIndex;
    public TreeNode buildTreeChild(int[] inorder, int[] postorder, int inbegin, int inend){
        if(inbegin > inend){
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findIndex(inorder,inbegin,inend,postorder[postIndex]);
        postIndex--;
        root.right = buildTreeChild(inorder,postorder,rootIndex + 1,inend);
        root.left = buildTreeChild(inorder,postorder,inbegin,rootIndex -1);

        return root;

    }

    private int findIndex(int[] inorder,int begin,int end,int val){
        for (int i = begin; i <= end; i++) {
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }

}
